<template>
  <div class="class-management">
    <h1>班级管理</h1>
    <br />

    <!-- 查询条件区域 -->
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="班级名称">
        <el-input v-model="searchForm.name" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="结课时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAddClass">
        <el-icon>
          <plus />
        </el-icon>
        新增班级
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="classList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column
        prop="name"
        label="班级名称"
        min-width="150"
        align="center"
      />
      <el-table-column
        prop="room"
        label="班级教室"
        width="120"
        align="center"
      />
      <el-table-column
        prop="masterName"
        label="班主任"
        width="120"
        align="center"
      />
      <el-table-column
        prop="beginDate"
        label="开课时间"
        width="150"
        align="center"
      />
      <el-table-column
        prop="endDate"
        label="结课时间"
        width="150"
        align="center"
      />
      <el-table-column prop="status" label="状态" width="120" align="center">
      </el-table-column>
      <el-table-column label="最后修改时间" width="180" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />

    <!-- 新增/编辑班级对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form
        :model="classForm"
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班级名称" prop="name">
              <el-input
                v-model="classForm.name"
                placeholder="请输入班级名称"
                style="width: 300px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班级教室" prop="classroom">
              <el-input
                v-model="classForm.room"
                placeholder="请输入班级教室"
                style="width: 300px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班主任">
              <el-select
                v-model="classForm.masterId"
                placeholder="请选择班主任"
                style="width: 300px"
              >
                <el-option
                  v-for="headTeacher in headTeachers"
                  :label="headTeacher.name"
                  :value="headTeacher.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="开课时间">
              <el-date-picker
                v-model="classForm.beginDate"
                type="date"
                placeholder="选择开课日期"
                value-format="YYYY-MM-DD"
                style="width: 300px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="结课时间" prop="endDate">
              <el-date-picker
                v-model="classForm.endDate"
                type="date"
                placeholder="选择结课日期"
                value-format="YYYY-MM-DD"
                style="width: 300px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="学科" prop="subjectId">
              <el-select
                v-model="classForm.subject"
                placeholder="请选择学科"
                style="width: 300px"
              >
                <el-option
                  v-for="subject in subjects"
                  :key="subject.id"
                  :label="subject.name"
                  :value="subject.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveClass">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import {
  queryClassListApi,
  addClassApi,
  updateClassApi,
  deleteClassApi,
  queryClassByIdApi,
} from "@/api/clazz";
import { Plus } from "@element-plus/icons-vue";
import { queryAllEmpApi } from "@/api/emp";

//日期格式
const formatDateTime = (data) => {
  return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
};

// 学科选项
const subjects = [
  { id: 1, name: "Java" },
  { id: 2, name: "前端" },
  { id: 3, name: "大数据" },
  { id: 4, name: "Python" },
  { id: 5, name: "Go" },
  { id: 6, name: "嵌入式" },
];

// 查询表单
const searchForm = ref({
  name: "",
  dateRange: [],
  begin: "",
  end: "",
});

// 班级列表数据
const classList = ref([]);

// 分页配置
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框控制
const dialogVisible = ref(false);
const dialogTitle = ref("新增班级");

// 班级表单
const classForm = ref({
  name: "",
  room: "",
  masterId: "",
  beginDate: "",
  endDate: "",
  subject: "", // 新增学科ID
});

// 表单验证规则
const rules = ref({
  name: [
    { required: true, message: "请输入班级名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在2到50个字符", trigger: "blur" },
  ],
  room: [{ required: true, message: "请输入班级教室", trigger: "blur" }],
  masterId: [
    { required: true, message: "请输入班主任姓名", trigger: "blur" },
  ],
  beginDate: [{ required: true, message: "请选择开课时间", trigger: "change" }],
  endDate: [{ required: true, message: "请选择结课时间", trigger: "change" }],
  subject: [{ required: true, message: "请选择学科", trigger: "change" }], // 新增学科验证
});

// 表单引用
const formRef = ref();

// 查询
const handleSearch = async () => {
  const result = await queryClassListApi(
    searchForm.value.name,
    searchForm.value.begin,
    searchForm.value.end,
    currentPage.value,
    pageSize.value
  );
  classList.value = result.data.rows;
  total.value = result.data.total;
};

// 重置查询
const resetSearch = () => {
  searchForm.value = {
    name: "",
    dateRange: [],
    begin: "",
    end: "",
  };
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  handleSearch();
};

// 当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  handleSearch();
};

//班主任数据
const headTeachers = ref([]);

// 新增班级
const handleAddClass = async () => {
  dialogTitle.value = "新增班级";
  dialogVisible.value = true;
  formRef.value?.resetFields();
  //表单数据
  classForm.value = {
    id: "",
    name: "",
    classroom: "",
    headTeacher: "",
    startDate: "",
    endDate: "",
    subjectId: "", // 重置学科ID
  };
};

// 编辑班级
const handleEdit = async (id) => {
  dialogTitle.value = "编辑班级";
  const result = await queryClassByIdApi(id);
  classForm.value = result.data;
  dialogVisible.value = true;
};

// 保存班级
const saveClass = async () => {
  await formRef.value.validate();
  let result;
  if (classForm.value.id) {
    result = await updateClassApi(classForm.value);
  } else {
    result = await addClassApi(classForm.value);
  }

  if (result.code === 1) {
    ElMessage.success("保存成功");
    dialogVisible.value = false;
    await handleSearch();
  } else {
    ElMessage.error(result.message);
  }
};

// 删除班级
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该班级吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const result = await deleteClassApi(row.id);
    if (result.code === 1) {
      ElMessage.success("删除成功");
      handleSearch();
    } else {
      ElMessage.error(result.msg);
    }
  });
};

// 监听日期范围变化
watch(
  () => searchForm.value.dateRange,
  (newVal) => {
    if (newVal && newVal.length === 2) {
      searchForm.value.begin = newVal[0];
      searchForm.value.end = newVal[1];
    } else {
      searchForm.value.begin = "";
      searchForm.value.end = "";
    }
  }
);

// 初始化加载数据
onMounted(async () => {
  await handleSearch();
  //导入班主任数据
  const result = await queryAllEmpApi();
  console.log(result.data);
  headTeachers.value = result.data;
});
</script>

<style scoped>
.class-management {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
```
